import { ForwardRefRenderFunction, useState, useEffect, useImperativeHandle, forwardRef, useCallback, memo, useMemo } from 'react'
import './style.less'
import { reqDbTables } from '@/api/assetMaintain/basicsData'
import { HsAdminForm, HsAdminInput, HsAdminSpin } from '@hs-admin/base-components'
import { Button, Row, Col, Form, DatePicker, Space, Flex } from 'antd'
import { HsAdminSelectTheme, HsAdminSelectUsers } from '@/components/global'
import { useImmer } from 'use-immer'
import { useSearchParams } from 'react-router-dom'
import dayjs from 'dayjs'
import { useTypeStore } from '@/store/useBasicDataItem'
import { reqCreateDataItem, reqEditDataItem, reqDataItemInfo } from '@/api/assetMaintain/basic/item'
import { message } from '@hs-admin/utils'

interface Props {
  back: () => void
  nextStep?: () => void
}

const Step1: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref: any) => {
  const { back } = props
  const [searchParams] = useSearchParams()
  const id: string | null = searchParams.get('id') || null
  const tabKey = useTypeStore((state) => state.tabKey)
  const setTabKey = useTypeStore((state) => state.setTabKey)
  const setDataItemId = useTypeStore((state) => state.setDataItemId)
  const setStatus = useTypeStore((state) => state.setStatus)

  const [form] = Form.useForm()
  const [formValues, setformValues] = useImmer<any>({
    plans: [{ date: '', description: '' }],
    helpers: [{ question: '', answer: '' }]
  })
  const [userOptions, setuserOptions] = useImmer<any[]>([])
  const [themeOptions, setthemeOptions] = useImmer<any[]>([])
  const [select_tableOptions, setselect_tableOptions] = useState([])
  const [isSave, setIsSave] = useState(false)
  const [loading, setloading] = useState(true)

  const formItemOptions = useMemo(
    () => [
      {
        label: '表选择',
        name: 'ref_table_name',
        component: 'Select',
        required: true,
        componentProps: {
          options: select_tableOptions,
          disabled: id || isSave
        },
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '数据项名称',
        name: 'name',
        component: 'Input',
        required: true,
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '数据项描述',
        name: 'description',
        component: 'TextArea',
        required: true,
        FormItemProps: {
          labelCol: { span: 3 },
          wrapperCol: { span: 21 }
        }
      },
      {
        label: '',
        name: 'title',
        slot: 'title'
      },
      {
        label: '所属主题',
        name: 'data_topics',
        slot: 'data_topics',
        required: true,
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '数据评分',
        name: 'score',
        component: 'InputNumber',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '负责人',
        name: 'contacts_id',
        slot: 'contacts_id',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '更新周期',
        name: 'update_frequency',
        component: 'Input',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '数据来源',
        name: 'source',
        component: 'Input',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '区域范围',
        name: 'area_scope',
        component: 'Input',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '数据时间范围',
        name: 'time_scope',
        component: 'Input',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '数据价格(元/条)',
        name: 'price',
        component: 'InputNumber',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '数据特征',
        name: 'data_characteristics',
        component: 'Select',
        componentProps: {
          options: [
            {
              label: '特色数据',
              value: '特色数据'
            },
            {
              label: '热门数据',
              value: '热门数据'
            }
          ],
          mode: 'multiple'
        },
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '支持数据的形式',
        name: 'supported_types',
        component: 'Select',
        componentProps: {
          options: [
            {
              label: '统计值',
              value: '统计值'
            },
            {
              label: '明细数据',
              value: '明细数据'
            }
          ],
          mode: 'multiple'
        },
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '完整度及计划',
        name: 'planSlot',
        slot: 'planSlot',
        FormItemProps: {
          labelCol: { span: 3 },
          wrapperCol: { span: 21 }
        }
      },
      {
        label: '帮助及问题',
        name: 'helperSlot',
        slot: 'helperSlot',
        FormItemProps: {
          labelCol: { span: 3 },
          wrapperCol: { span: 21 }
        }
      }
    ],
    [id, isSave, select_tableOptions]
  )

  const addHelp = () => {
    setformValues((prev: any) => {
      prev.helpers.push({
        question: '',
        answer: ''
      })
    })
  }
  const deleteHelp = (index: any) => {
    if (formValues.helpers.length === 1) {
      message.warning('至少保留一条!')
      return
    }
    setformValues((prev: any) => {
      prev.helpers.splice(index, 1)
    })
  }
  const addPlan = () => {
    setformValues((prev: any) => {
      prev.plans.push({
        date: dayjs().format('YYYY-MM-DD'),
        description: ''
      })
    })
  }
  const deletePlan = (index: any) => {
    if (formValues.plans.length === 1) {
      message.warning('请至少填写当前完整度及计划!')
      return
    }
    setformValues((prev: any) => {
      prev.plans.splice(index, 1)
      if (prev.plans.length === 1) {
        prev.plans[0].date = ''
      }
    })
  }
  const dateChange = (_date: dayjs.Dayjs | null, dateString: string, index: number) => {
    setformValues((prev: any) => {
      prev.plans[index].date = dateString
    })
  }
  // 获取表列表
  const getDbTables = useCallback(async () => {
    const res = await reqDbTables({ page_size: 1000 })
    const list = res.items.map((item: any) => ({
      label: item.name,
      value: item.name
    }))
    if (id) {
      list.unshift({
        label: formValues.ref_table_name,
        value: formValues.ref_table_name
      })
    }
    setselect_tableOptions(list)
    setloading(false)
  }, [formValues.ref_table_name, id])

  const init = async () => {
    setloading(true)
    if (id) {
      const params = {
        id
      }
      const data = await reqDataItemInfo(params)
      const model = {
        ...data,
        data_characteristics: data.data_characteristics.filter((item: any) => item) ?? [],
        supported_types: data.supported_types.filter((item: any) => item) ?? [],
        helpers: data.helpers,
        plans: [{ date: '', description: data.current_integrity }, ...data.plans],
        contacts_id: data.contacts_id || undefined,
        data_topics: data.data_topics.map((item: { id: any }) => item.id)
      }
      setformValues(model)
      form.setFieldsValue(model)
      setthemeOptions(
        data.data_topics.map((item: { name: any; id: any }) => ({
          label: item.name,
          value: item.id
        }))
      )
      if (model.contacts) {
        setuserOptions([
          {
            label: model.contacts.name,
            value: model.contacts.id
          }
        ])
      }
      setStatus(model.status)
      getDbTables()
    } else {
      getDbTables()
    }
  }

  const goStep2 = async () => {
    form
      .validateFields()
      .then(async (values) => {
        if (isSave) {
          setTabKey('2')
          return
        }
        setloading(true)
        const [firstPlan, ...remainPlans] = formValues.plans
        const params = {
          id: formValues.id,
          current_integrity: firstPlan.description,
          plans: remainPlans,
          helpers: formValues.helpers,
          ...values,
          supported_types: values.supported_types ?? [],
          data_characteristics: values.data_characteristics ?? [],
          update_frequency: values.update_frequency ?? '',
          source: values.source ?? '',
          area_scope: values.area_scope ?? '',
          time_scope: values.time_scope ?? '',
          contacts_id: values.contacts_id ?? '',
          price: values.price ?? null,
          score: values.score ?? 0
        }
        if (!id) {
          reqCreateDataItem(params)
            .then((res) => {
              setDataItemId(res.id)
              setTabKey('2')
              setIsSave(true)
            })
            .catch((error) => {
              return Promise.reject(error)
            })
            .finally(() => {
              setloading(false)
            })
        } else {
          reqEditDataItem(params)
            .then(() => {
              setTabKey('2')
            })
            .finally(() => {
              setloading(false)
            })
        }
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
  const cancel = useCallback(async () => {
    setformValues({})
    form.resetFields()
    setDataItemId(null)
  }, [form, setDataItemId, setformValues])

  useEffect(() => {
    if (tabKey === '1') {
      init()
    }
  }, [tabKey])

  useImperativeHandle(
    ref,
    () => {
      return {
        cancel
      }
    },
    [cancel]
  )

  return (
    <div className="operation-basic-data-item-setp1">
      {loading && <HsAdminSpin />}
      <HsAdminForm form={form} formItemOptions={formItemOptions} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="right">
        <div slot="title">
          <Row>
            <Col span={4}>
              <h3>数据项信息</h3>
            </Col>
          </Row>
        </div>
        <div slot="data_topics">
          <HsAdminSelectTheme placeholder="请选择所属主题" options={themeOptions} mode="multiple" />
        </div>
        <div slot="contacts_id">
          <HsAdminSelectUsers placeholder="请选择负责人" options={userOptions} />
        </div>
        <div slot="planSlot">
          <div className="mt-2">
            {formValues.plans?.map((item: any, index: number) => (
              <Row key={index} gutter={[12, 12]} className="plan-row">
                <Col span={8}>
                  {!index && <span>当前</span>}
                  {index > 0 && (
                    <DatePicker value={dayjs(item.date)} className="w-full" onChange={(date, dateString) => dateChange(date, dateString, index)} />
                  )}
                </Col>
                <Col span={8}>
                  <Flex align="center" gap={'small'}>
                    <span className="flex-none w-7"></span>
                    <HsAdminInput
                      TextArea
                      autoSize={{ minRows: 3, maxRows: 8 }}
                      value={item.description}
                      onChange={(e: { target: { value: string } }) => {
                        setformValues((prev: { plans: { description: string }[] }) => {
                          prev.plans[index].description = e.target.value
                        })
                      }}
                    />
                  </Flex>
                </Col>
                <Col span={8}>
                  <Space>
                    <Button type="primary" danger onClick={() => deletePlan(index)}>
                      删除
                    </Button>
                    {!index && (
                      <Button type="primary" onClick={() => addPlan()}>
                        新增
                      </Button>
                    )}
                  </Space>
                </Col>
              </Row>
            ))}
          </div>
        </div>
        <div slot="helperSlot">
          <div>
            {formValues.helpers?.map((item: any, index: number) => (
              <Row key={index} gutter={[12, 12]} className="plan-row">
                <Col span={8}>
                  <Flex align="center" gap={'small'}>
                    <span className="flex-none">问题{index + 1}</span>
                    <HsAdminInput
                      value={item.question}
                      onChange={(e: { target: { value: string } }) => {
                        setformValues((prev: { helpers: { question: string }[] }) => {
                          prev.helpers[index].question = e.target.value
                        })
                      }}
                    />
                  </Flex>
                </Col>
                <Col span={8}>
                  <Flex gap={'small'}>
                    <span className="flex-none leading-8">回复</span>
                    <HsAdminInput
                      TextArea
                      value={item.answer}
                      autoSize={{ minRows: 3, maxRows: 8 }}
                      onChange={(e: { target: { value: string } }) => {
                        setformValues((prev: { helpers: { answer: string }[] }) => {
                          prev.helpers[index].answer = e.target.value
                        })
                      }}
                    />
                  </Flex>
                </Col>
                <Col span={8}>
                  <Space>
                    <Button type="primary" danger onClick={() => deleteHelp(index)}>
                      删除
                    </Button>
                    {!index && (
                      <Button type="primary" onClick={() => addHelp()}>
                        新增
                      </Button>
                    )}
                  </Space>
                </Col>
              </Row>
            ))}
          </div>
        </div>
      </HsAdminForm>
      <Space className="flex justify-end">
        <Button onClick={back}>取消</Button>
        {id && (
          <Button type="primary" onClick={goStep2}>
            保存
          </Button>
        )}
        {!id && (
          <Button type="primary" onClick={goStep2}>
            下一步
          </Button>
        )}
      </Space>
    </div>
  )
}

export default memo(forwardRef(Step1))
